package com.bappi.utils;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class HttpUtils {
	private static final int HTTP_TIMEOUT = 30 * 1000;

	public static final byte[] getHttpResponse(String url) throws IOException {
		HttpClient client = getHttpClient();
		HttpGet request = new HttpGet(url);
		HttpResponse response = client.execute(request);
		return EntityUtils.toByteArray(response.getEntity());
	}
	public static final String getHttpResponseAsString(String url) throws IOException {
		HttpClient client = getHttpClient();
		HttpGet request = new HttpGet(url);
		HttpResponse response = client.execute(request);
		return EntityUtils.toString(response.getEntity());
	}
	private static HttpClient mHttpClient;

	private static HttpClient getHttpClient() {
		if (mHttpClient == null) {
			mHttpClient = new DefaultHttpClient();
			final HttpParams params = mHttpClient.getParams();
			HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
			HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
			ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
		}
		return mHttpClient;
	}
	
	public static boolean isDeviceOnline(Context context) {
		boolean ret = true;
		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo i = cm.getActiveNetworkInfo();
		if (i == null || (!i.isConnected()) || (!i.isAvailable())) {
			ret = false;
		}
		return ret;
	}

}
